local protobuf = require "protobuf"

local game_cmd = require "cmd_def"


local M = {}
M.PROTO_FILE = {
    "./proto/export/lua/common.pb",
    "./proto/export/lua/combat.pb",
    "./proto/export/lua/scene.pb",
    "./proto/export/lua/player.pb",

    "./proto/export/lua/account_service.pb",
    "./proto/export/lua/common_service.pb",
    "./proto/export/lua/player_service.pb",
    "./proto/export/lua/scene_service.pb",
}
M.registed_files = {}

M.CLIENT_CMD_HANDLER = {
    [game_cmd.CLIENT_CMD.LOGIN] = "service.account.LoginRequest",
    [game_cmd.CLIENT_CMD.LOGOUT] = "",
    [game_cmd.CLIENT_CMD.REGIST] = "service.account.RegisterRequest",
    [game_cmd.CLIENT_CMD.GET_PLAYER_BASE_INFO] = "service.player.GetPlayerBaseInfoRequest",
    [game_cmd.CLIENT_CMD.ENTER_DEFAULT_SCENE] = "service.scene.RequestEnterDefaultScene",
    [game_cmd.CLIENT_CMD.MOVE] = "service.scene.RequestMove",
    [game_cmd.CLIENT_CMD.USE_SKILL] = "service.scene.RequestUseSkill",
}

M.SERVER_CMD_HANDLER = {
    [game_cmd.SERVER_CMD.COMMON] = "service.common.CommonResponse",
    [game_cmd.SERVER_CMD.LOGIN_RESPONSE] = "service.account.LoginRequest.Response",
    [game_cmd.SERVER_CMD.REGIST_RESPONSE] = "service.account.RegisterRequest.Response",
    [game_cmd.SERVER_CMD.PLAYER_BASE_INFO] = "service.player.GetPlayerBaseInfoRequest.Response",
    [game_cmd.SERVER_CMD.ENTER_DEFAULT_SCENE_RESPONSE] = "service.scene.RequestEnterDefaultScene.Response",
    [game_cmd.SERVER_CMD.MOVE] = "service.scene.RequestMove.Response",
    [game_cmd.SERVER_CMD.USE_SKILL_RESPONSE] = "service.scene.RequestUseSkill.Response",
}


function M.regist_all_proto_files()
    for _, file in pairs(M.PROTO_FILE) do
        print("regist proto file:" .. file)
        M.regist_proto_file(file)
    end
end

function M.regist_proto_file(file)
    if not M.registed_files[file] then
        protobuf.register_file(file)
        M.registed_files[file] = true
    end
end

function M.get_client_protobuf_type(cmd)
    return M.CLIENT_CMD_HANDLER[cmd]
end

function M.get_server_protobuf_type(cmd)
    return M.SERVER_CMD_HANDLER[cmd]
end

function M.decode(type, origin_data)
    if not origin_data then
        return
    end

    local success, msg = pcall(protobuf.decode, type, origin_data, string.len(origin_data))
    if not success then
        return
    end

    return msg
end

function M.encode(type, origin_data)
    local pack = protobuf.encode(type, origin_data)
    return pack
end


return M